import areaService from '@/api/area/index.js'
import { ref } from 'vue'

export function useAreaData() {
  const areaList = ref([])
  const isLoading = ref(false)
  const error = ref(null)

  const fetchCityData = async () => {
    try {
      isLoading.value = true
      const response = await areaService.getAreaList()
      areaList.value = response.data
    }
    catch (err) {
      error.value = err.message
    }
    finally {
      isLoading.value = false
    }
  }

  const findAreaNamesByCode = (ids) => {
    const result = []
    // 定义递归函数
    function search(items) {
      items.forEach((item) => {
        if (ids.includes(item.code)) {
          result.push(item.name)
        }
        if (item.children && item.children.length > 0) {
          search(item.children) // 递归搜索子项
        }
      })
    }
    search(areaList.value) // 从顶层数组开始搜索
    return result
  }

  return {
    areaList,
    isLoading,
    error,
    fetchCityData,
    findAreaNamesByCode,
  }
}
